﻿namespace MicroCloud.AspNetCore.Mvc
{
    /// <summary>
    /// MicroCloud控制器基类，配置了操作审计，API属性，授权属性
    /// </summary>
    [AuditOperation]
    [ApiController]
    [ApiAuthorize]
    public abstract class ControllerBase : Microsoft.AspNetCore.Mvc.ControllerBase
    {
        #region 属性
        /// <summary>
        /// 获取 服务提供者对象
        /// </summary>
        protected virtual IServiceProvider ServiceProvider => HttpContext.RequestServices;

        /// <summary>
        /// 获取 日志对象
        /// </summary>
        protected virtual ILogger Logger => ServiceProvider.GetLogger(GetType());
 
        /// <summary>
        /// 获取 过滤表达式功能
        /// </summary>
        protected virtual IFilterService FilterService => ServiceProvider.GetService<IFilterService>();

        /// <summary>
        /// 获取 数据权限服务
        /// </summary>
        protected virtual IDataAuthService DataAuthService => ServiceProvider.GetService<IDataAuthService>();

        /// <summary>
        /// 获取 缓存服务功能
        /// </summary>
        protected virtual ICacheService CacheService => ServiceProvider.GetService<ICacheService>();

        /// <summary>
        /// 获取 HttpClient工厂对象
        /// </summary>
        protected virtual IHttpClientFactory HttpClientFactory => ServiceProvider.GetService<IHttpClientFactory>();

        /// <summary>
        /// 获取 当前组织机构编号
        /// </summary>
        protected virtual string CurrentOrganizationId
        {
            get
            {
                if (User.Identity?.IsAuthenticated != true)
                {
                    return null;
                }
                return User.Identity.GetCurrentOrganizationId();
            }
        }

        /// <summary>
        /// 获取 当前部门机构编号
        /// </summary>
        protected virtual string CurrentDepartmentId
        {
            get
            {
                if (User.Identity?.IsAuthenticated != true)
                {
                    return null;
                }
                return User.Identity.GetCurrentDepartmentId();
            }
        }

        #endregion

        #region 方法
        /// <summary>
        /// 创建一个HttpClient
        /// </summary>
        /// <param name="clientName">要创建的客户端的逻辑名称</param>
        /// <returns></returns>
        [NonAction]
        [NonFunction]
        protected virtual HttpClient CreateHttpClient(string clientName = "")
        {
            if (!clientName.IsMissing())
            {
                return HttpClientFactory.CreateClient(clientName);
            }
            return HttpClientFactory.CreateClient();
        }

        #endregion

    }

}